﻿using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Drawing;
using System.Windows.Media.Imaging;

namespace WhiteRepositoryExplorer.Converters
{
    public class ImageNameToPathConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var name = values[0] as string;
            var pathToXml = values[1] as string;
            if (name == null || pathToXml == null) return null;
            var pathToImageFolder = Path.GetDirectoryName(pathToXml) + "\\images\\";
            var fullPathToImage= Path.GetFullPath(pathToImageFolder + name);
            if (File.Exists(pathToImageFolder + name)) return LoadImageFromDisk(fullPathToImage);
            var imageResource = Application.Current.FindResource("PlaceholderImage") as System.Windows.Controls.Image;
            return imageResource.Source;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private BitmapImage LoadImageFromDisk(string imagePath)
        {
            var bmp = (Bitmap)Image.FromFile(imagePath);
            var result = new BitmapImage();

            using (var memStream = new MemoryStream())
            {
                bmp.Save(memStream, bmp.RawFormat);
                memStream.Position = 0;

                result.BeginInit();
                result.StreamSource = memStream;
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
            }

            return result;
        }
    }
}
